package com.mrzhou.auth.config;

import com.mrzhou.auth.handler.*;
import com.mrzhou.auth.provider.LoginAuthenticationProvider;
import com.mrzhou.auth.service.IntegrationUserDetailsImpl;
import com.mrzhou.auth.support.CloudPasswordEncoderFactory;
import com.mrzhou.auth.utils.TokenUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.HashMap;
import java.util.Map;

@Configuration
@Slf4j
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private IntegrationUserDetailsImpl integrationUserDetailsService;

    @Bean
    @Override
    @SneakyThrows
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 用户在不同类型下, 需要使用的密码检查类
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        Map<String, CheckHandler> checkHandlerMap = new HashMap<>();

        // 使用自定义的Provider
        LoginAuthenticationProvider loginAuthenticationProvider = new LoginAuthenticationProvider(integrationUserDetailsService);
        checkHandlerMap.put(TokenUtil.AUTH_PSW, new UsernamePasswordCheckHandler(this.passwordEncoder()));
        checkHandlerMap.put(TokenUtil.AUTH_QR, new QrCheckHandler());
        checkHandlerMap.put(TokenUtil.AUTH_CODE, new AuthCodeCheckHandler());
        checkHandlerMap.put(TokenUtil.AUTH_SMS, new MailPhoneCodeCheckHandler());
        loginAuthenticationProvider.setCheckHandlerMap(checkHandlerMap); // 添加支持的密码检验处理类
        auth.authenticationProvider(loginAuthenticationProvider); // 自定义登录密码验证类
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic().and().csrf().disable();
    }


    @Bean
    public PasswordEncoder passwordEncoder() {
        return CloudPasswordEncoderFactory.createDelegatingPasswordEncoder();
    }

}
